package com.example.simple_android.controller;

import com.example.simple_android.annotation.InitElement;

import java.lang.reflect.Field;

import lombok.Getter;

public abstract class AbstractController<T> implements Controller<T> {

    @Getter
    protected T target;

    protected Class<? extends Controller<T>> clazz;

    public AbstractController() {
        super();
        this.clazz = (Class<? extends Controller<T>>) this.getClass();
    }

    public AbstractController(T target) {
        this.clazz = (Class<? extends Controller<T>>) this.getClass();
        init(target);
    }

    @Override
    public void init(T target) {
        this.target = target;
    }

    @Override
    public void initTargetElement(T target) {
        // 寻找类中所有的Field
        Field[] fields = clazz.getDeclaredFields();
        // 遍历每个Field，查看是否存在指定注解
        for (Field field : fields) {
            InitElement initElement = field.getDeclaredAnnotation(InitElement.class);
            if (initElement == null) {
                continue;
            }
            // 存在指定主句，获取指定注解，并且获取绑定值
            int elementId = initElement.elementId();
            // 通过findElement方法获取element
            Object element = findElement(elementId);
            if (element == null) {
                continue;
            }
            field.setAccessible(true);
            try {
                // 向Field中注入element
                field.set(this, element);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
